# @File: run_testcase.py
# -*- coding: utf-8 -*-
# __author:"super"
# @time:2025/7/27 19:12
import os
import sys
from typing import List

from get_testcases.config_handlers import handle_dist_strategy_yaml
from hook_manager import cli_hook
from tools._printer import print_message
from tools.log import AoMakerLogger


def _handle_login(skip_login: bool):
    if skip_login is True:
        return
    sys.path.append(os.getcwd())
    # Todo 登录要改
    exec('from login import Login')
    login_obj = locals()['Login']()
    return login_obj


def _handle_dist_mode(d_mark, d_file, d_suite):
    if d_mark:
        if isinstance(d_mark, str):
            d_mark = d_mark.split(" ")
        params = [f"-m {mark}" for mark in d_mark]
        mode_msg = "dist-mark"
        print_message(f":hammer_and_wrench: 分配模式: {mode_msg}")
        return params

    if d_file:
        params = {"path": d_file}
        mode_msg = "dist-file"
        print_message(f":hammer_and_wrench: 分配模式: {mode_msg}")
        return params

    if d_suite:
        params = d_suite
        mode_msg = "dist-suite"
        print_message(f":hammer_and_wrench: 分配模式: {mode_msg}")
        return params

    params = handle_dist_strategy_yaml()
    mode_msg = "dist-mark(dist_strategy.yaml策略)"
    print_message(f":hammer_and_wrench: 分配模式: {mode_msg}")
    return params


def main_run(env: str = None,
             log_level: str = "info",
             mp: bool = False,
             mt: bool = False,
             d_suite: str = None,
             d_file: str = None,
             d_mark: str = None,
             skip_login: bool = False,
             no_gen: bool = True,
             pytest_args: List[str] = None,
             processes: int = None,
             **custom_kwargs):
    # print(__image__)
    cli_hook.custom_kwargs = custom_kwargs
    cli_hook()
    if cli_hook.custom_kwargs:
        cli_hook.run()

    if pytest_args is None:
        pytest_args = []

    if log_level != "info":
        print_message(f":wrench:切换日志等级：{log_level}")
        AoMakerLogger.change_level(log_level)

    login_obj = _handle_login(skip_login)

    task_args = None
    run_mode = "main"
    if mp or mt:
        run_mode = "mp" if mp else "mt"
        task_args = _handle_dist_mode(d_mark, d_file, d_suite)

    from get_testcases.runner import run_tests, RunConfig

    run_config = RunConfig(
        env=env,
        run_mode=run_mode,
        task_args=task_args,
        pytest_args=pytest_args,
        login_obj=login_obj,
        report_enabled=no_gen,
        processes=processes
    )

    run_tests(run_config)


if __name__ == '__main__':
    main_run(env="mock", pytest_args=['-m mock_api'])
